package com.zyh.dao.impl;

import com.zyh.dao.IUserDao;
import com.zyh.domain.User;
import com.zyh.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class UserDaoImpl implements IUserDao {

    @Override
    public int addUser(User user) throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        String sql = "insert into user (username, password, name, intro) values (?,?,?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        int i = 1;
        preparedStatement.setString(i++, user.getUsername());
        preparedStatement.setString(i++, user.getPassword());
        preparedStatement.setString(i++, user.getName());
        preparedStatement.setString(i++, user.getIntro());

        int result = preparedStatement.executeUpdate();

        preparedStatement.close();
        conn.close();
        return result;
    }

    @Override
    public User getUserByUserName(String username) throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        String sql = "select * from user where username = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, username);

        ResultSet rs = preparedStatement.executeQuery();

        List<User> list = getUserListByResultSet(rs);

        preparedStatement.close();
        conn.close();
        return !list.isEmpty() ? list.get(0) : null;
    }

    private List<User> getUserListByResultSet(ResultSet rs) throws SQLException {
        List<User> list = new ArrayList<User>();
        while (rs.next()) {
            list.add(new User(
                    rs.getInt("id"),
                    rs.getString("username"),
                    rs.getString("password"),
                    rs.getString("name"),
                    rs.getString("intro")
            ));
        }
        return list;
    }
}
